package android.app.gfestival;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.gfestival.adapter.DbHelper;
import android.app.gfestival.component.ArtistViewSwicher;
import android.app.gfestival.soap.Artist;
import android.app.gfestival.soap.ArtistDescription;
import android.app.gfestival.soap.SoapParserHelper;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;

public class ArtistActivity extends Activity{
	private static final String TAG = "ArtistActivity";
	private static final String URL_RSS = "http://www.gfestival.fo/index.php?id=1&type=100";
	private SQLiteDatabase db;
	private ArtistViewSwicher view;
	final DbHelper helper = new DbHelper(this);
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		dialog = createProgressDialog(this.getParent(), R.style.ProgressDialogSpinner);
		dialog.show();
		new ArtistsAsynTask().execute(null);
		
	}
	
	private ProgressDialog createProgressDialog(Activity context, int style){
		ProgressDialog dialog = new ProgressDialog(context,style);
		dialog.setMessage("Loading...");
		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		return dialog;
	}
	
	@Override
	protected void onDestroy() {
		db.close();
		super.onDestroy();
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode != KeyEvent.KEYCODE_BACK) return super.onKeyDown(keyCode, event);
		if(view.showPreviou() < 0 ){
			getParent().finish();
		}
		return false;
	}
	
	private class ArtistsAsynTask extends AsyncTask<String, String, Cursor>{

		@Override
		protected Cursor doInBackground(String... params) {
			
			return loadData();
		}
		
		@Override
		protected void onPostExecute(Cursor result) {
			// TODO Auto-generated method stub
			showData(result);
		}
	}

	public void showData(Cursor result) {
		view = new ArtistViewSwicher(this, result);
		setContentView(view);
		dialog.dismiss();
	}

	public Cursor loadData() {
		db = helper.getWritableDatabase();
		List<ArtistDescription> artists = new ArrayList<ArtistDescription>();
		db.delete(DbHelper.TABLE_ARTIST, null, null);
		try {
			artists = SoapParserHelper.getAllArtistHaveEvents();
		} catch (Exception e) {
			e.printStackTrace();
		}
		int eff = helper.insertData(db, artists);
		
		Cursor cursor = db.query(DbHelper.TABLE_ARTIST, null, null, null, null, null, DbHelper.ARTIST_NAME + " ASC");
		startManagingCursor(cursor);
		return cursor;
	}
}
